package com.sos.service.impl;

import com.sos.exception.CustomException;
import com.sos.exception.ErrorCode;
import com.sos.model.entity.User;
import com.sos.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 自定义UserDetailsService实现
 * 用于Spring Security认证时查询自定义用户表
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    /**
     * 根据用户名/手机号查询用户信息（Spring Security认证时自动调用）
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 先通过用户名查询，不存在则尝试通过手机号查询
        User user = userRepository.findByUsername(username)
                .orElseGet(() -> userRepository.findByPhone(username)
                        .orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)));

        // 2. 检查用户是否被禁用
        if (user.getStatus() == 0) {
            throw new CustomException(ErrorCode.USER_DISABLED);
        }

        // 3. 封装为Spring Security需要的UserDetails对象
        // 注意：这里的权限集合暂时为空，后续如需角色权限控制可添加
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),  // 数据库中存储的加密后密码
                Collections.emptyList()  // 权限列表
        );
    }
}
